package com.iflytek.uoamp.agent.monitor.job;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;

import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.MonitorItemConfig;
import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.MonitorItemResult;
import com.iflytek.uoamp.agent.monitor.dump.PSInfoCache;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentConfig;
import com.iflytek.uoamp.agent.monitor.mcagent.MonitorResultSender;

@DisallowConcurrentExecution
public class ServerMonitorJob implements Job {

	private JobExecutionContext context;
	private ArrayList<String> taskIDs;
	private String jobDescription;
	private JobKey jobKey;
	

	/**
	 * get need parse job
	 * */
	private final void initJobInfo() {
		jobKey = context.getJobDetail().getKey();
		jobDescription = context.getJobDetail().getDescription();
		taskIDs = new ArrayList<String>();
		Set<String> nameList = MCAgentJobManager.getSchedulerMonitorMap().get(jobKey);
		taskIDs.addAll(nameList);
		
		Logger.getRootLogger().info("ServerMonitorJob init job finish and execute " + jobDescription + ":" + MCAgentConfig.getInstance().getMonitoredPointIp() + " Start Monitor " + taskIDs.size() + " Services " + taskIDs);
	}

	/**
	 * 创建一个错误对象
	 * @param config
	 * @return
	 */
	public static MonitorItemResult createErrorResult(MonitorItemConfig config){
		MonitorItemResult result = new MonitorItemResult();
		result.setComponentType("checklocal");
		result.setHost(config.getHost());
		result.setServerDesc(config.getServerDesc());
		result.setReturnCode(1+"");
		result.setOutput("脚本执行出现异常，请检查系统环境");
		result.setUptime(config.getUptime());
		return result;
	}
	
	/**
	 * do monitor and add result to List<MonitorItemResult>
	 * */
	private List<MonitorItemResult> doMonit() {
		List<MonitorItemResult> monitorResults = new ArrayList<MonitorItemResult>();
		for (String serviceID : taskIDs) {
			MonitorItemConfig config = Cache.readCache(MCAgentJobManager.getITEMTYPE(),serviceID);
			Logger.getRootLogger().info("read "+serviceID+"  and read result is "+(config!=null));
			if(config==null){
				continue;
			}
			ShellExecutor shellExrcutor = new ShellExecutor(config);
			MonitorItemResult result = shellExrcutor.check();
//			if (null != result) {
				Logger.getRootLogger().info("ServerMonitorJob getMonitorResults Service " + serviceID + " return_code:" + result.getReturnCode() + " output: " + result.getOutput());
				result.setSendhost(MCAgentConfig.getInstance().getMonitoredPointIp());
				monitorResults.add(result);
				//记录上一次的状态；
				PSInfoCache.getInstance().putPsInfo(result, config);
//			} else {
//				Logger.getRootLogger().error("ServerMonitorJob getMonitorResults Service " + serviceID + " return monitor result is null and command is "+shellExrcutor.getCommand());
//				monitorResults.add(createErrorResult(config));
//			}
		}
		return monitorResults;
	}

	
	
	/**
	 * 执行方法;重载父类方法以被调用;
	 * @param context
	 * @exception JobExecutionException
	 * @return
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {
		
		long startTime = System.currentTimeMillis();
		this.context = context;
		initJobInfo();

		List<MonitorItemResult> monitorResults = doMonit();
		MonitorResultSender.getInstance().addMonitorResult(jobKey, monitorResults);

		// record every runtime
		long excuteTime = System.currentTimeMillis() - startTime;
		Logger.getRootLogger().info("ServerMonitorJob execute " + jobDescription + ":" + MCAgentConfig.getInstance().getMonitoredPointIp() + " Excute Time " + excuteTime / 1000);
	}
	
}
